<template>
  <common-layout>
    <div class="top">
      <div class="header">
        <img alt="logo" class="logo" src="@/assets/img/logo.png"/>
        <span class="title">{{ systemName }}</span>
      </div>
      <div class="desc">Ant Design 是西湖区最具影响力的 Web 设计规范</div>
    </div>
    <div class="login">
      <a-form @submit="onSubmit" :form="form">
        <a-tabs size="large" :tabBarStyle="{textAlign: 'center'}" style="padding: 0 2px;">
          <a-tab-pane key="1" tab="账户登录">
            <a-alert type="error" :closable="true" v-if="error" :message="error" @close='onClose' showIcon
                     style="margin-bottom: 24px;"/>
            <a-form-item>
              <a-input
                  autocomplete="autocomplete"
                  size="large"
                  placeholder="请输入账号"
                  v-decorator="['name', {rules: [{ required: true, message: '请输入账户名', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="user"/>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                  size="large"
                  placeholder="请输入密码"
                  autocomplete="autocomplete"
                  type="password"
                  v-decorator="['password', {rules: [{ required: true, message: '请输入密码', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="lock"/>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-row :gutter="8" style="margin: 0 -4px">
                <a-col :span="16">
                  <a-input size="large"
                           placeholder="请输入验证码"
                           autocomplete="autocomplete"
                           v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码', whitespace: true}]}]">
                    <a-icon slot="prefix" type="mail"/>
                  </a-input>
                </a-col>
                <a-col :span="8" style="padding-left: 34px;margin-top: 3px">
                  <img :src="captcha" alt="验证码" height="35" style="vertical-align:inherit;" @click="refreshCaptcha"/>
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
        <div>
          <a-checkbox :checked="true">自动登录</a-checkbox>
          <a style="float: right">忘记密码</a>
        </div>
        <a-form-item>
          <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit"
                    type="primary">登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from '@/layouts/CommonLayout'
import {login, getCaptcha} from '@/services/user'
import {setAuthorization} from '@/utils/request'
import {loadRoutes} from '@/utils/routerUtil'
import {mapMutations} from 'vuex'
import {v4 as uuidv4} from 'uuid'
import md5 from 'js-md5'

export default {
  name: 'Login',
  components: {CommonLayout},
  data() {
    return {
      logging: false,
      error: '',
      form: this.$form.createForm(this),
      captcha: '@/assets/img/logo.png'
    }
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName
    }
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    onSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          const name = this.form.getFieldValue('name')
          const password = this.form.getFieldValue('password')
          const captcha = this.form.getFieldValue('captcha')
          console.log(captcha);
          const uuid = this.getUuid();
          login(name, md5(password), captcha, uuid).then(this.afterLogin)
        }
      })
    },
    afterLogin(res) {
      this.logging = false
      const loginRes = res.data
      if (loginRes.code === "SUCCESS") {
        const respData = loginRes.data;
        setAuthorization({token: respData.token, expireAt: new Date(new Date().getTime() + 30 * 60 * 1000)})

        const user = {
          name: respData.userName,
          avatar: '@/assets/img/logo.png',
          address: '@CITY',
          position: '@POSITION'
        };
        this.setUser(user) //设置用户信息

        const permissions = [{id: 'permissions', operation: respData.permissions}]
        this.setPermissions(permissions)

        // 获取路由配置
        console.log(respData)
        const routers = [{
          router: "root",
          children: respData.routers
        }]
        loadRoutes(routers);

        this.$router.push('/Index')
        this.$message.success("登陆成功，欢迎" + respData.userName + "回来!", 3)
      } else {
        this.error = loginRes.msg
        this.refreshCaptcha();
      }
    },
    onClose() {
      this.error = false
    },
    refreshCaptcha() {
      let uuid = this.getUuid()
      getCaptcha(uuid).then(result => {
        console.log(result.data);
        if (result.data.code === "SUCCESS") {
          this.captcha = result.data.data;
        }
        // //localStorage.setItem(process.env.VUE_APP_USER_KEY, JSON.stringify(user))
        // console.log(uuid);
      })
    },
    getUuid() {
      let uuid = sessionStorage.getItem('uuid');
      if (!uuid) {
        uuid = uuidv4();
        sessionStorage.setItem('uuid', uuid);
      }
      return uuid;
    }
  },
  created() {
    this.refreshCaptcha();
  }
}
</script>

<style lang="less" scoped>
.common-layout {
  .top {
    text-align: center;

    .header {
      height: 44px;
      line-height: 44px;

      a {
        text-decoration: none;
      }

      .logo {
        height: 44px;
        vertical-align: top;
        margin-right: 16px;
      }

      .title {
        font-size: 33px;
        color: @title-color;
        font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
      }
    }

    .desc {
      font-size: 14px;
      color: @text-color-second;
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }

  .login {
    width: 368px;
    margin: 0 auto;
    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }

    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
  }
}
</style>
